/*******************************************************************************
 * Copyright (c) 2011 Erik Byström.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package se.slackers.automatunes.algorithm;

import java.awt.Dimension;

/**
 * @author Erik Byström
 * 
 */
public class Field {
	public static final float LIVE = 1;
	public static final float DEAD = 0;

	private final Dimension size;
	private final float[] data;
	private boolean wrapping = false;

	public Field(final Dimension size) {
		this.size = size;
		data = new float[size.width * size.height];
	}

	public Field wrap(final boolean value) {
		wrapping = value;
		return this;
	}

	public int width() {
		return size.width;
	}

	public int height() {
		return size.height;
	}

	public void clear(final float value) {
		for (int i = 0; i < data.length; i++) {
			data[i] = value;
		}
	}

	public float get(int x, int y) {
		if (wrapping) {
			if (x < 0) {
				x += size.width;
			}
			if (y < 0) {
				y += size.height;
			}

			x = x % size.width;
			y = y % size.height;
		} else if (x < 0 || y < 0 || x >= size.width || y >= size.height) {
			return 0;
		}

		return data[x + y * size.width];
	}

	public float get(final int index) {
		return data[index];
	}

	public float sumNeigbours(final int x, final int y) {
		float neighbours = 0;
		for (int dy = -1; dy <= 1; dy++) {
			for (int dx = -1; dx <= 1; dx++) {
				if (dx != 0 || dy != 0) {
					neighbours += get(x + dx, y + dy);
				}
			}
		}
		return neighbours;
	}

	public void set(int x, int y, final float value) {
		if (wrapping) {
			if (x < 0) {
				x += size.width;
			}
			if (y < 0) {
				y += size.height;
			}

			x = x % size.width;
			y = y % size.height;
		} else if (x < 0 || y < 0 || x >= size.width || y >= size.height) {
			return;
		}

		data[x + y * size.width] = value;
	}

	public void set(final int index, final float value) {
		data[index] = value;
	}

	public void copy(final Field f) {
		// TODO: handle fields of different size?
		for (int i = 0; i < data.length; i++) {
			data[i] = f.data[i];
		}
	}
}
